package com.jfs.zlk.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.annotation.JSONField;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * @Description http工具类
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/27
 */
public class HttpUtils {
    /**
     * 格式化路径参数 可选参数
     *
     * @param uri uri
     * @param map map
     * @return initUriPathParams
     * @throws UnsupportedEncodingException 异常
     */
    public static String initUriPathParams(String uri, Map<String, Object> map) throws UnsupportedEncodingException {
        String key;
        String value;
        StringBuilder builder = new StringBuilder();
        builder.append(uri);
        builder.append("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            key = entry.getKey();
            value = String.valueOf(entry.getValue());
            String tmpKv;
            tmpKv = String.format(Locale.ROOT, "%s=%s&", URLEncoder.encode(key, StandardCharsets.UTF_8.name()),
                    URLEncoder.encode(value, StandardCharsets.UTF_8.name()));
            builder.append(tmpKv);
        }
        return builder.toString();
    }

    /**
     * 格式化路径参数 可选参数
     *
     * @param url
     * @param o
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String initUriPathParams(String url, Object o, Class<?> clazz) throws UnsupportedEncodingException, IllegalAccessException {
        Map<String, Object> params = new HashMap<>();
        //获取类所有字段
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields
        ) {
            field.setAccessible(true);
            Object fileValue = field.get(o);
            if (Objects.nonNull(fileValue)) {
                if (field.isAnnotationPresent(JSONField.class)) {
                    JSONField annotation = field.getAnnotation(JSONField.class);
                    String name = annotation.name();
                    if (StrUtil.isNotEmpty(name)) {
                        params.put(name, fileValue);
                    }
                } else {
                    String name = field.getName();
                    params.put(name, fileValue);
                }
            }
        }
        return initUriPathParams(url, params);
    }
}
